import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { VitePWA } from 'vite-plugin-pwa'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
    plugins: [
      vue({
        script: {
          defineModel: true,
          propsDestructure: true
        }
      }),
      
      // PWA配置
      VitePWA({
        registerType: 'autoUpdate',
        workbox: {
          globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
          runtimeCaching: [
            {
              urlPattern: /^https:\/\/api\./,
              handler: 'NetworkFirst',
              options: {
                cacheName: 'api-cache',
                networkTimeoutSeconds: 3,
                cacheableResponse: {
                  statuses: [0, 200]
                }
              }
            },
            {
              urlPattern: /\.(png|jpg|jpeg|svg|gif|webp)$/,
              handler: 'CacheFirst',
              options: {
                cacheName: 'image-cache',
                expiration: {
                  maxEntries: 100,
                  maxAgeSeconds: 60 * 60 * 24 * 30 // 30天
                }
              }
            }
          ]
        },
        manifest: {
          name: '家庭媒体管理系统',
          short_name: '家庭媒体',
          description: '智能家庭媒体管理和分享平台',
          theme_color: '#6366f1',
          background_color: '#ffffff',
          display: 'standalone',
          orientation: 'portrait-primary',
          start_url: '/',
          icons: [
            {
              src: '/icons/icon-192x192.png',
              sizes: '192x192',
              type: 'image/png'
            },
            {
              src: '/icons/icon-512x512.png',
              sizes: '512x512',
              type: 'image/png'
            },
            {
              src: '/icons/icon-512x512.png',
              sizes: '512x512',
              type: 'image/png',
              purpose: 'maskable'
            }
          ]
        }
      }),
      
      // 压缩插件
      viteCompression({
        algorithm: 'gzip',
        ext: '.gz',
        deleteOriginFile: false
      }),
      
      viteCompression({
        algorithm: 'brotliCompress',
        ext: '.br',
        deleteOriginFile: false
      }),
      
      // 包分析
      process.env.ANALYZE && visualizer({
        filename: 'dist/stats.html',
        open: true,
        gzipSize: true
      })
    ],
    
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
        '@components': resolve(__dirname, './src/components'),
        '@views': resolve(__dirname, './src/views'),
        '@composables': resolve(__dirname, './src/composables'),
        '@utils': resolve(__dirname, './src/utils'),
        '@stores': resolve(__dirname, './src/stores'),
        '@api': resolve(__dirname, './src/api'),
        '@assets': resolve(__dirname, './src/assets')
      }
    },
    
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@/assets/styles/variables.scss";`
        }
      }
    },
    
    build: {
      target: ['es2015', 'safari11'],
      cssTarget: 'chrome61',
      
      // 代码分割优化
      rollupOptions: {
        output: {
          manualChunks: {
            // 将vendor库分离
            'vendor-vue': ['vue', 'vue-router', 'pinia'],
            'vendor-ui': ['@opentiny/vue'],
            'vendor-utils': ['axios', 'dayjs', 'lodash-es'],
            
            // 按功能模块分离
            'mobile-components': [
              './src/components/mobile/MobileUploader.vue',
              './src/components/mobile/MobileMediaGrid.vue'
            ],
            'mobile-views': [
              './src/views/mobile/MediaDetailView.vue',
              './src/views/mobile/FamilyManageView.vue'
            ],
            'composables': [
              './src/composables/useResponsive.ts',
              './src/composables/useTouch.ts',
              './src/composables/usePerformance.ts'
            ]
          }
        }
      },
      
      // 压缩配置
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
          pure_funcs: ['console.log', 'console.info']
        }
      },
      
      // 资源处理
      assetsInlineLimit: 4096,
      chunkSizeWarningLimit: 1000,
      
      // 构建输出目录
      outDir: 'dist/mobile',
      emptyOutDir: true
    },
    
    server: {
      host: '0.0.0.0',
      port: 3000,
      strictPort: false,
      open: false,
      cors: true,
      
      // 开发服务器代理
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    
    preview: {
      port: 3001,
      strictPort: false,
      open: false,
      cors: true
    },
    
    // 优化配置
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'pinia',
        '@opentiny/vue',
        'axios',
        'dayjs'
      ],
      exclude: ['@vueuse/core']
    },
    
    define: {
      __VUE_OPTIONS_API__: false,
      __VUE_PROD_DEVTOOLS__: false
    }
  }
})